package com.lancoo.klgcourseware.ui.fragment.klgSubjectFragment;

import android.Manifest;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;

import com.lancoo.klgcourseware.R;
import com.lancoo.klgcourseware.base.BaseKlgFragment;
import com.lancoo.klgcourseware.ui.activity.KlgCourseWareMainActivity;
import com.lancoo.klgcourseware.ui.widget.OnScrollListener;
import com.lancoo.klgcourseware.utils.KlgToolUtils;


/**
 * Created by pengmi on 2019/8/14 15:13
 * Description:
 */
public abstract class SubjectKnowledgeFragment extends BaseKlgFragment {

    protected String klgCode;
    protected boolean expandTrain,enableShowSign;

    protected final int MSG_SIGN_ALERT=10;
    protected LoadDataSuccess loadDataSuccess;
    protected OnScrollListener onScrollListener;



    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        klgCode=getArguments().getString(KlgCourseWareMainActivity.KEY_KLGCODE);
        expandTrain=getArguments().getBoolean(KlgCourseWareMainActivity.KEY_EXPANDTRAIN,true);
        super.onViewCreated(view, savedInstanceState);
        enableShowSign=true;
    }



    protected void setTitleName(String titleName){
        if(getActivity() instanceof KlgCourseWareMainActivity){
            ((KlgCourseWareMainActivity)getActivity()).setKlgName(titleName);
        }
    }

    private void showSignAlert(){
        if(!enableShowSign){
            return;
        }
//        enableShowSign=false;
        if(getContext()==null){
            return;
        }
        View inflate = LayoutInflater.from(getContext()).inflate(R.layout.klg_dialog_sign_light_ring, null);
        final AlertDialog.Builder builder=new AlertDialog.Builder(getContext(),R.style.klg_NoBgColorStyle);
        builder.setView(inflate);
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.dimAmount=0.1f;

        window.setAttributes(attributes);
        final ImageView img_ring = inflate.findViewById(R.id.img_ring);
        final ImageView img_sign = inflate.findViewById(R.id.img_sign);
        showFlowAnimation(img_ring);
        showFlowAnimation1(img_sign);
        img_ring.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(System.currentTimeMillis()-time<500){
                    return;
                }
                time=System.currentTimeMillis();
                if(verifyPermissions(getActivity())){
                    enterBasicTrain();
                }
                if(alertDialog!=null&&alertDialog.isShowing()){
                    alertDialog.dismiss();
                }
            }
        });
        inflate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(alertDialog!=null&&alertDialog.isShowing()){
                    alertDialog.dismiss();
                }
            }
        });
        alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if(img_ring!=null){
                    img_ring.clearAnimation();
                    img_sign.clearAnimation();
                }

            }
        });

    }



    protected void showSign(){
        if(!enableShowSign){
            return;
        }
        if(!expandTrain){
            return;
        }
        mHandler.removeMessages(MSG_SIGN_ALERT);
        mHandler.sendEmptyMessageDelayed(MSG_SIGN_ALERT,15*1000);
    }

    private void showFlowAnimation(ImageView img){
        if(!expandTrain){
            return;
        }
        img.clearAnimation();
        ObjectAnimator scaleX=ObjectAnimator.ofFloat(img, View.SCALE_X,1f,1.1f,1f);
        ObjectAnimator scaleY=ObjectAnimator.ofFloat(img,View.SCALE_Y,1f,1.1f,1f);
//        ObjectAnimator alpha = ObjectAnimator.ofFloat(img, View.ALPHA, 1f, 1.2f);
        scaleX.setRepeatCount(-1);
//        scaleX.setRepeatMode(ValueAnimator.INFINITE);
        scaleY.setRepeatCount(-1);
//        scaleY.setRepeatMode(ValueAnimator.INFINITE);
//        alpha.setRepeatCount(-1);
//        alpha.setRepeatMode(ValueAnimator.INFINITE);
        AnimatorSet animatorSet=new AnimatorSet();
        animatorSet.playTogether(scaleX,scaleY);
        animatorSet.setDuration(1000);
        animatorSet.start();
    }
    private void showFlowAnimation1(ImageView img){
        img.clearAnimation();
        int dp10= KlgToolUtils.dip2px(getContext(),7);
        ObjectAnimator scaleX=ObjectAnimator.ofFloat(img, View.TRANSLATION_X,0f,dp10,0);
        ObjectAnimator scaleY=ObjectAnimator.ofFloat(img,View.TRANSLATION_Y,0f,dp10,0);
//        ObjectAnimator alpha = ObjectAnimator.ofFloat(img, View.ALPHA, 1f, 1.2f);
        scaleX.setRepeatCount(-1);
//        scaleX.setRepeatMode(ValueAnimator.INFINITE);
        scaleY.setRepeatCount(-1);
//        scaleY.setRepeatMode(ValueAnimator.INFINITE);
//        alpha.setRepeatCount(-1);
//        alpha.setRepeatMode(ValueAnimator.INFINITE);
        AnimatorSet animatorSet=new AnimatorSet();
        animatorSet.playTogether(scaleX,scaleY);
        animatorSet.setDuration(1000);
        animatorSet.start();
    }


    protected Handler mHandler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what){
                case MSG_SIGN_ALERT:
                    showSignAlert();
                    break;
            }
            return false;
        }
    });

    @Override
    public void onPause() {
        super.onPause();
        mHandler.removeMessages(MSG_SIGN_ALERT);

    }


    protected boolean verifyPermissions(Activity activity) {
        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)

                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
//            Toast.makeText(activity.getApplicationContext(), "没有获取权限,请手动开启权限", Toast.LENGTH_SHORT).show();
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 100);//,Manifest.permission.READ_PHONE_STATE
            return false;
        }else{
            return true;
        }
    }

    public void setLoadDataSuccess(LoadDataSuccess loadDataSuccess){
        this.loadDataSuccess=loadDataSuccess;
    }

    public void setOnScrollListener(OnScrollListener onScrollListener){
        this.onScrollListener=onScrollListener;
    }

    protected void enterBasicTrain(){}

    protected void pauseMedia(){}

    public interface  LoadDataSuccess{
        void onLoadSuccess();
        void onLoadFailure();
        void onSoundPlay();

    }

    public void pauseMediaPlay(){
        pauseMedia();
    }

    public void removeConnection(){}

}
